
package cn.dankal.basiclib.common.share.mob;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;

import com.tencent.connect.share.QQShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import cn.dankal.basiclib.DankalApplication;
import cn.dankal.basiclib.R;
import cn.dankal.basiclib.base.callback.DKCallBack;
import cn.dankal.basiclib.util.CheckApkExist;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.util.Util;

/**
 * Created by Zoro丶源 on 2016/12/3.
 */

public class ShareDialog2 extends Dialog {
    private DKCallBack callBack;
    private Context context;
    private String title, text, img, url;
    private ImageView ivQQ, ivWechat, ivWeibo, ivQuze, ivWeChatFrient;
    private static final String ID = "?share_id=";
    private static final String TOKEN = "&token=";
    private static final String IMG = "&img=";
    private String uuid;
    private IWXAPI api;
    private ShareMessage shareMessage;

    private String mUrl = "http://fg-share.dankal.cn/detail?uuid=";

    private Tencent myTencent;
    private ShareUiListener mIUiListener;

    private static final String baseUrl = "http://share.inffur.com";


    public ShareDialog2(Context context, String text, String uuid, DKCallBack callBack) {
        this(context, 0);
        this.context = context;
        this.text = text;
        this.uuid = uuid;
        this.callBack = callBack;
    }

    public void releaseMemory() {
        this.context = null;
    }


    public void setShareMessage(ShareMessage shareMessage) {
        this.shareMessage = shareMessage;
    }

    public ShareDialog2(Context context, int themeResId) {
        super(context, themeResId);
        this.context = context;
    }

    public ShareDialog2 setText(String text) {
        this.text = text;
        return this;
    }


    public ShareDialog2 setUrl(String id, String token, String img) {
        this.url = baseUrl + ID + id + TOKEN + token + IMG + img;
        return this;
    }

    public ShareDialog2 setTitle(String title) {
        this.title = title;
        return this;
    }


    /**
     * 自定义监听器实现IUiListener，需要3个方法
     * onComplete完成 onError错误 onCancel取消
     */
    private class ShareUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            //分享成功
            ToastUtils.showShort("分享成功！");
            dismiss();
            callBack.action();
        }

        @Override
        public void onError(UiError uiError) {
            //分享失败
            ToastUtils.showShort("分享失败！");
            dismiss();
            callBack.action();
        }

        @Override
        public void onCancel() {
            //分享取消
            ToastUtils.showShort("分享取消！");
            dismiss();
            callBack.action();
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myTencent = DankalApplication.instance().getTencent();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        title = "此刻";

        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_share, null);
        ivQQ = dialogView.findViewById(R.id.iv_qq_1);
        ivQuze = dialogView.findViewById(R.id.iv_quze);
        ivWechat = dialogView.findViewById(R.id.iv_wechat);
        ivWeChatFrient = dialogView.findViewById(R.id.iv_wechatfriend);
        ivWeibo = dialogView.findViewById(R.id.iv_weibo);

        api = DankalApplication.instance().getIWXAPI();

        ivWechat.setOnClickListener(v ->
                ivWeChat(1)
        );
        ivWeChatFrient.setOnClickListener(v ->
                ivWeChat(2)
        );

        ivQQ.setOnClickListener(v ->
                QQShare()
        );

        ivQuze.setOnClickListener(v ->
                QQQuze()
        );

        ivWeibo.setOnClickListener(v -> {
            if (shareMessage != null) {
                shareMessage.onClickShare(3);
            }
        });


        dialogView.findViewById(R.id.iv_close).setOnClickListener(v ->
                {
                    dismiss();
                    callBack.action();

                }
        );

        //获得dialog的window窗口
        Window window = this.getWindow();                //设置dialog在屏幕底部
        window.setGravity(Gravity.CENTER);                //设置dialog弹出时的动画效果，从屏幕底部向上弹出
//      window.getDecorView().setPadding(0, 0, 0, 0);                //获得window窗口的属性
//      WindowManager.LayoutParams lp = window.getAttributes();                //设置窗口宽度为充满全屏
//      lp.width = AutoUtils.getPercentWidthSize(500);                //设置窗口高度为包裹内容
//      lp.height = AutoUtils.getPercentHeightSize(400);                //将设置好的属性set回去
//      window.setAttributes(lp);
        setContentView(dialogView);

    }

    //分享到朋友圈或者朋友圈
    private void ivWeChat(int type) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = mUrl + uuid;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = "此刻 ";
        msg.description = text;
        Bitmap thumbBmp = BitmapFactory.decodeResource(context.getResources(), R.mipmap.qq_refresh_success);
        msg.thumbData = Util.bmpToByteArray(thumbBmp, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        if (type == 1) {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }
        api.sendReq(req);
    }

    //分享到QQ
    private void QQShare() {
        if (!CheckApkExist.checkqqExist(context)) {
            ToastUtils.showShort("您还未安装手机QQ，暂不能分享！");
            return;
        }
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, text);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, mUrl + uuid);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "https://www.bugdone.cn/images/logo/logoshort0.png");
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "飞歌");
        myTencent.shareToQQ((Activity) context, params, mIUiListener);
    }

    private void QQQuze() {
        mIUiListener = new ShareUiListener();
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);//分享的类型
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title);//分享标题
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, text);//要分享的内容摘要
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, mUrl + uuid);//内容地址
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "https://www.bugdone.cn/images/logo/logoshort0.png");//分享的图片URL
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "飞歌");//应用名称
        myTencent.shareToQQ((Activity) context, params, mIUiListener);
    }

    public interface ShareMessage {
        void onClickShare(int type);
    }
}
